package com.cssnj.portal.utils;

import com.google.common.primitives.Chars;
import io.predictech.framework.domain.exception.BaseException;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 获取中文拼音工具类
 *
 * @author Arthur
 * @version 1.0
 * @since 2018-9-18 11:10
 */
public class PinYinUtils {
    /**
     * 得到 全拼
     */
    public static String getPinYin(String src) {
        String[] tempStrArray;
        HanyuPinyinOutputFormat pinyinOutputFormat = new HanyuPinyinOutputFormat();
        pinyinOutputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        pinyinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        pinyinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        StringBuilder backStr = new StringBuilder();
        try {
            for (char aT1 : src.toCharArray()) {
                // 判断是否为汉字字符
                if ((aT1 >= 0x4e00) && (aT1 <= 0x9fbb)) {
                    tempStrArray = PinyinHelper.toHanyuPinyinStringArray(aT1, pinyinOutputFormat);
                    backStr.append(tempStrArray[0]);
                } else {
                    backStr.append(Character.toString(aT1));
                }
            }
            return backStr.toString();
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            PortalUntil.logger().error("拼音转换失败 e : " + e.getMessage());
        }
        return backStr.toString();
    }

    /**
     * 得到中文首字母
     */
    public static String getPinYinHeadChar(String str) {
        //设置大写
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        StringBuffer convert = new StringBuffer();

        Chars.asList(str.toCharArray()).forEach(tarStr -> {
            String[] pinyinArray = null;
            try {
                pinyinArray = PinyinHelper.toHanyuPinyinStringArray(tarStr, format);
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                PortalUntil.logger().error("拼音转换失败 e : " + e.getMessage());
            }
            if (null != pinyinArray) {
                convert.append(pinyinArray[0].charAt(0));
            } else {
                convert.append(tarStr);
            }
        });

        return convert.toString();
    }
}
